package com.siriuscloud.holidayreservation.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siriuscloud.holidayreservation.domain.Department;
import com.siriuscloud.holidayreservation.service.DepartmentService;
import com.siriuscloud.holidayreservation.utils.MyPage;
import com.siriuscloud.holidayreservation.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
public class DepartmentController {

    @Resource
    private DepartmentService departmentService;

    @GetMapping("/departments/all")
    public R list() throws Exception {
        try {
            List<Department> departments = departmentService.getAll();
            return R.ok().data(departments);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    @GetMapping("/departments/page")
    public R getAllByPage(MyPage page, @RequestParam(required = false) String name) {
        Page<Department> allByPage = departmentService.getAllByPage(page, name);
        HashMap<String, Object> data = new HashMap<>();
        data.put("total", allByPage.getTotal());
        data.put("rows", allByPage.getRecords());
        return R.ok().data(data);
    }

    @PostMapping("/department")
    public R add(@RequestBody Department department) throws Exception {
        Boolean flag = departmentService.create(department);
        if (flag) {
            return R.ok().msg("新增成功");
        }
        return R.error().msg("新增失败");
    }

    @PutMapping("/department")
    public R update(@RequestBody Department department) {
        Boolean flag = departmentService.update(department);
        if (flag) {
            return R.ok().msg("修改成功");
        }
        return R.error().msg("修改失败");
    }

    @DeleteMapping("/department/{id}")
    public R delete(@PathVariable String id) {
        Boolean flag = departmentService.delete(id);
        if (flag) {
            return R.ok().msg("删除成功");
        }
        return R.error().msg("删除失败");
    }

    @GetMapping("/department/{id}")
    public R get(@PathVariable String id) {
        Department department = departmentService.getDepartmentById(id);
        return R.ok().data(department);
    }
}
